import styles from './index.module.scss'
import React, { memo, useEffect, useState } from 'react'
import ArticleItem from '@/components/ArticleItem'
import { useDispatch } from 'react-redux'
import { getNewListData } from '../../store/action'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile-v5'
import { useSelector } from 'react-redux'

export default memo(function ArticleList({ id, activeId }) {
  const dispatch = useDispatch()
  const ChannelsObj = useSelector(
    (state) => state.HomeReducer.articles[activeId]
  )

  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)
  const loadMore = async () => {
    if (!ChannelsObj) return
    if (loading) return
    setLoading(true)
    if (!ChannelsObj.timestamp) {
      setHasMore(false)
      return
    }
    try {
      await dispatch(getNewListData(activeId, ChannelsObj.timestamp, true))
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    if (id === activeId) {
      if (!ChannelsObj) {
        dispatch(getNewListData(activeId, Date.now()))
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeId, dispatch, id])
  return (
    <div className={styles.root}>
      <div className="am-pull-to-refresh">
        <PullToRefresh
          onRefresh={async () =>
            await dispatch(getNewListData(activeId, Date.now()))
          }
        >
          {ChannelsObj &&
            ChannelsObj.list.map((i, index) => (
              <div className="article-item" key={index}>
                <ArticleItem {...i} />
              </div>
            ))}
        </PullToRefresh>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </div>
    </div>
  )
})
